package com.idea.relax.log.config;

import com.idea.relax.log.props.RelaxLogProperties;
import com.idea.relax.log.support.ConditionalMultiple;
import com.idea.relax.log.trace.DefaultTraceIdGenerator;
import com.idea.relax.log.trace.FeignRequestInterceptor;
import com.idea.relax.log.trace.ITraceIdGenerator;
import com.idea.relax.log.trace.TrackerFilter;
import org.springframework.boot.autoconfigure.condition.*;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.*;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import javax.servlet.DispatcherType;


/**
 * @className: TrackerAutoConfiguration
 * @description: 链路日志自动配置类
 * @author: salad
 * @date: 2023/1/23
 **/
@Order
@EnableConfigurationProperties({RelaxLogProperties.class})
public class TrackerAutoConfiguration {


	@Bean("traceIdGenerator")
	@ConditionalOnMissingBean(name = "traceIdGenerator")
	@ConditionalOnProperty(
		value = {
			RelaxLogProperties.PREFIX + RelaxLogProperties.ENABLED,
			RelaxLogProperties.RequestLog.PREFIX + ".enabled-trace-mode"
		}, havingValue = "true"
	)
	public ITraceIdGenerator traceIdGenerator() {
		return new DefaultTraceIdGenerator();
	}


	@Bean("logTraceFilterRegistration")
	@ConditionalOnProperty(
		value = {
			RelaxLogProperties.PREFIX + RelaxLogProperties.ENABLED,
			RelaxLogProperties.RequestLog.PREFIX + ".enabled-trace-mode"
		}, havingValue = "true"
	)
	public FilterRegistrationBean<TrackerFilter> logTraceFilterRegistration(ITraceIdGenerator traceIdGenerator) {
		FilterRegistrationBean<TrackerFilter> registration = new FilterRegistrationBean<>();
		registration.setDispatcherTypes(DispatcherType.REQUEST);
		registration.setFilter(new TrackerFilter(traceIdGenerator));
		registration.addUrlPatterns("/*");
		registration.setName("trackerFilter");
		registration.setOrder(Ordered.LOWEST_PRECEDENCE);
		return registration;
	}

	@Order
	@Configuration(
		proxyBeanMethods = false
	)
	@ConditionalMultiple(
		classNames = "feign.RequestInterceptor",
		attributes = {
			RelaxLogProperties.PREFIX + RelaxLogProperties.ENABLED,
			RelaxLogProperties.RequestLog.PREFIX + ".enabled-trace-mode"
		}, havingValues = {"true","true"})
	public static class FeignRequestInterceptorConfiguration {

		@Bean("feignRequestInterceptor")
		public FeignRequestInterceptor feignRequestInterceptor(RelaxLogProperties properties) {
			return new FeignRequestInterceptor(properties);
		}

	}


}
